package com.changpei.common.result;

import com.changpei.common.result.enums.CommonCode;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;

import java.io.Serializable;

/**
 *
 *
 * @author Way on 2021/7/16
 */
@Data
public class Result<T> implements Serializable {

    private static final long serialVersionUID = 5005318709330004756L;

    /**
     * 状态码
     */
    private Integer code;

    /**
     * 描述
     */
    private String msg;

    /**
     * 结果集
     */
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private T data;

    /**
     * 当前访问url
     */
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private String url;

    public static <T> Result<T> ok() {
        return restResult(CommonCode.SUCCESS, null, null);
    }

    public static <T> Result<T> ok(T data) {
        return restResult(CommonCode.SUCCESS, null, data);
    }

    public static <T> Result<T> failed() {
        return restResult(CommonCode.SERVER_INTERNAL_ERROR, null, null);
    }

    public static <T> Result<T> failed(CommonCode commonCode) {
        return restResult(commonCode, null, null);
    }

    public static <T> Result<T> failed(CommonCode commonCode, String url) {
        return restResult(commonCode, url, null);
    }

    private static <T> Result<T> restResult(CommonCode commonCode, String url, T data) {
        Result<T> result = new Result<>();
        result.setCode(commonCode.code());
        result.setMsg(commonCode.message());
        result.setUrl(url);
        result.setData(data);
        return result;
    }
}
